import {get, post} from './http.js';

$(document).ready(function () {
    // 初始化订单列表
    renderOrders('all');

    // 标签切换事件
    $('.tab-item').click(function () {
        $('.tab-item').removeClass('active');
        $(this).addClass('active');

        const status = $(this).data('status');
        renderOrders(status);
    });
});

// 渲染订单列表
async function renderOrders(status) {
    const $orderList = $('.order-list');
    $orderList.empty();

    let orderData = await get('/api/order/my/' + status);

    // 筛选订单
    let orders = orderData;

    // 渲染订单
    orders.forEach(order => {
        const orderHtml = `
            <div class="order-item" data-order-id="${order.id}">
                <div class="order-header">
                    <div class="order-info">
                        <span>订单号：${order.id}</span>
                        <span>下单时间：${order.date}</span>
                    </div>
                    <div class="order-status">${getStatusText(order.status)}</div>
                </div>
                <div class="order-content">
                    ${renderProducts(order.products)}
                </div>
                <div class="order-footer">
                    <div class="order-total">
                        实付金额：<span class="amount">¥${order.totalAmount.toFixed(
            2)}</span>
                    </div>
                    <div class="order-actions">
                        ${renderActions(order)}
                    </div>
                </div>
            </div>
        `;
        $orderList.append(orderHtml);
    });
}

// 渲染商品列表
function renderProducts(products) {
    return products.map(product => `
        <div class="product-item">
            <div class="product-img">
                <img src="${product.image}" alt="${product.title}">
            </div>
            <div class="product-info">
                <div class="product-title">${product.title}</div>
                <div class="product-spec">${product.spec}</div>
            </div>
            <div class="product-price">¥${product.price.toFixed(2)}</div>
            <div class="product-count">x${product.count}</div>
        </div>
    `).join('');
}

// 渲染订单操作按钮
function renderActions(order) {
    switch (order.status) {
        case 'unpaid':
            return `
                <button class="btn-pay">立即付款</button>
                <button class="btn-view">查看详情</button>
            `;
        case 'unshipped':
            return `<button class="btn-view">查看详情</button>`;
        case 'shipped':
            return `
                <button class="btn-view">查看物流</button>
                <button class="btn-confirm">确认收货</button>
            `;
        case 'completed':
            return `<button class="btn-view">查看详情</button>`;
        default:
            return '';
    }
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'unpaid': '待付款',
        'unshipped': '待发货',
        'shipped': '待收货',
        'completed': '已完成'
    };
    return statusMap[status] || status;
}

// 订单操作函数
function payOrder(orderId) {
    // 获取订单信息
    alert('支付订单：' + orderId)

    // window.location.href = `payment.html?orderId=${orderId}&amount=${order.totalAmount}&paymentMethod=alipay`;
    // window.location.href = `payment.html?orderId=${orderNo}&amount=${amount}&paymentMethod=${paymentMethod}&codeUrl=${codeUrl}`;
}

async function viewOrder(orderId) {
    createOrderDetailModal(await get(`/api/order/detail/${orderId}`));
}

function confirmReceive(orderId) {
    // 确认收货
    if (confirm('确认已收到商品？')) {
        post('/api/order/receive/' + orderId).then(data => {
            renderOrders('shipped');
        })
    }
}

// 绑定付款按钮
$('.order-list').on('click', '.btn-pay', function () {
    const orderId = $(this).closest('.order-item').data('order-id');
    payOrder(orderId);
});

// 绑定查看详情按钮
$('.order-list').on('click', '.btn-view', function () {
    const orderId = $(this).closest('.order-item').data('order-id');
    viewOrder(orderId);
});

// 绑定确认收货按钮
$('.order-list').on('click', '.btn-confirm', function () {
    const orderId = $(this).closest('.order-item').data('order-id');
    confirmReceive(orderId);
})

// 生成查看详情界面，展示用户信息，订单信息，商品信息，物流信息，优惠信息
// 创建订单详情模态框
function createOrderDetailModal(orderDetail) {
    const modalHtml = `
        <div class="modal order-detail-modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>订单详情</h2>
                    <span class="close">&times;</span>
                </div>
                <div class="modal-body">
                    <!-- 用户信息 -->
                    <div class="detail-section user-info">
                        <h3>用户信息</h3>
                        <div class="info-item">
                            <span class="label">用户名:</span>
                            <span class="value">${orderDetail.user.name}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">联系电话:</span>
                            <span class="value">${orderDetail.user.phone}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">收货地址:</span>
                            <span class="value">${orderDetail.user.address}</span>
                        </div>
                    </div>
                    
                    <!-- 订单信息 -->
                    <div class="detail-section order-info">
                        <h3>订单信息</h3>
                        <div class="info-item">
                            <span class="label">订单号:</span>
                            <span class="value">${orderDetail.id}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">下单时间:</span>
                            <span class="value">${orderDetail.date}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">订单状态:</span>
                            <span class="value">${getStatusText(orderDetail.status)}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">支付方式:</span>
                            <span class="value">${orderDetail.paymentMethod || '未支付'}</span>
                        </div>
                    </div>
                    
                    <!-- 商品信息 -->
                    <div class="detail-section product-info">
                        <h3>商品信息</h3>
                        <div class="product-list">
                            ${orderDetail.products.map(product => `
                                <div class="product-detail-item">
                                    <div class="product-img">
                                        <img src="${product.image}" alt="${product.title}">
                                    </div>
                                    <div class="product-details">
                                        <div class="product-title">${product.title}</div>
                                        <div class="product-spec">${product.spec}</div>
                                        <div class="product-price-info">
                                            <span class="price">¥${product.price.toFixed(2)}</span>
                                            <span class="count">x${product.count}</span>
                                        </div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                        <div class="order-summary">
                            <div class="summary-item">
                                <span>商品总价:</span>
                                <span>¥${orderDetail.totalAmount.toFixed(2)}</span>
                            </div>
                            <div class="summary-item">
                                <span>运费:</span>
                                <span>¥${(orderDetail.shippingFee || 0).toFixed(2)}</span>
                            </div>
                            <div class="summary-item">
                                <span>优惠金额:</span>
                                <span>-¥${(orderDetail.discount || 0).toFixed(2)}</span>
                            </div>
                            <div class="summary-item total">
                                <span>实付金额:</span>
                                <span>¥${(orderDetail.finalAmount || orderDetail.totalAmount).toFixed(2)}</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 物流信息 -->
                    <div class="detail-section logistics-info">
                        <h3>物流信息</h3>
                        ${orderDetail.logistics ? `
                            <div class="logistics-details">
                                <div class="info-item">
                                    <span class="label">物流公司:</span>
                                    <span class="value">${orderDetail.logistics.company}</span>
                                </div>
                                <div class="info-item">
                                    <span class="label">物流单号:</span>
                                    <span class="value">${orderDetail.logistics.trackingNumber}</span>
                                </div>
                                <div class="shipping-status">
                                    <div class="status-item">
                                        <div class="status-dot"></div>
                                        <div class="status-text">已发货</div>
                                        <div class="status-time">${orderDetail.logistics.shippedTime}</div>
                                    </div>
                                    <div class="status-item">
                                        <div class="status-dot"></div>
                                        <div class="status-text">运输中</div>
                                        <div class="status-time">${orderDetail.logistics.inTransitTime || ''}</div>
                                    </div>
                                    <div class="status-item">
                                        <div class="status-dot"></div>
                                        <div class="status-text">已送达</div>
                                        <div class="status-time">${orderDetail.logistics.deliveredTime || ''}</div>
                                    </div>
                                </div>
                            </div>
                        ` : `
                            <div class="no-logistics">
                                暂无物流信息
                            </div>
                        `}
                    </div>
                    
                    <!-- 优惠信息 -->
                    <div class="detail-section discount-info">
                        <h3>优惠信息</h3>
                        ${orderDetail.coupons && orderDetail.coupons.length > 0 ? `
                            <div class="coupons-list">
                                ${orderDetail.coupons.map(coupon => `
                                    <div class="coupon-item">
                                        <div class="coupon-name">${coupon.name}</div>
                                        <div class="coupon-value">优惠¥${coupon.value.toFixed(2)}</div>
                                        <div class="coupon-code">${coupon.code}</div>
                                    </div>
                                `).join('')}
                            </div>
                        ` : `
                            <div class="no-coupons">
                                无优惠券使用
                            </div>
                        `}
                    </div>
                </div>
            </div>
        </div>
    `;

    // 添加到页面中
    $('body').append(modalHtml);

    // 绑定关闭事件
    $('.order-detail-modal .close').click(function () {
        $('.order-detail-modal').remove();
    });

    // 点击模态框外部关闭
    $('.order-detail-modal').click(function (e) {
        if (e.target === this) {
            $(this).remove();
        }
    });
}